import { configureStore } from '@reduxjs/toolkit';
import userReducer from './slices/userSlice';
import networkReducer from './slices/networkSlice';

// 检查是否有缓存的网络状态
const loadNetworkState = () => {
  try {
    const serializedState = localStorage.getItem('networkState');
    if (serializedState === null) {
      return undefined; // 如果没有缓存，返回undefined让reducer使用默认状态
    }
    return JSON.parse(serializedState);
  } catch (err) {
    console.error('加载网络状态失败:', err);
    return undefined;
  }
};

// 保存网络状态到localStorage
const saveNetworkState = (state) => {
  try {
    const serializedState = JSON.stringify(state);
    localStorage.setItem('networkState', serializedState);
  } catch (err) {
    console.error('保存网络状态失败:', err);
  }
};

// 创建store
export const store = configureStore({
  reducer: {
    user: userReducer,
    network: networkReducer,
  },
  preloadedState: {
    // 只有在有缓存时才加载缓存的状态
    network: loadNetworkState(),
  },
});

// 订阅store变化，保存网络状态
store.subscribe(() => {
  const state = store.getState();
  saveNetworkState(state.network);
});
